package com.hmall.controller;

import com.hdmall.business.common.annotation.LoginRequired;
import com.hdmall.business.common.common.Const;
import com.hdmall.business.common.common.ResponseCode;
import com.hdmall.business.common.common.ServerResponse;
import com.hdmall.business.common.util.JsonUtils;
import com.hmall.mapper.SysDeptCustomerMapper;
import com.hmall.model.SysUser;
import com.hmall.service.BiUserActionHistoryService;
import com.hmall.service.CartService;
import com.hmall.util.TokenUtil;
import com.hmall.vo.BiActionHisParamsVo;
import com.hmall.vo.CartTemVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("cart/")
@Api(value = "购物车操作API", description = "购物车类API说明")
public class CartController {

    @Autowired
    private CartService iCartService;

    @Autowired
    private BiUserActionHistoryService actionHistoryService;

    @Autowired
    private SysDeptCustomerMapper sysDeptCustomerMapper;

    @Autowired
    JedisPool jedisPool;

    TokenUtil tokenUtil = new TokenUtil();

    @LoginRequired
    @PostMapping("selectCartProducts")
    @ApiOperation(value = "购物车产品列表")
    public ServerResponse<CartTemVo> selectCartProducts(String token) throws Exception {

        Jedis jedis = jedisPool.getResource();
        SysUser user = tokenUtil.tokenToUser(jedis, token).getData();
        jedis.close();
        return iCartService.selectCartProducts(user.getUserId());
    }

    //商家全选与取消选择
    @LoginRequired
    @PostMapping("selectionByShop")
    @ApiOperation(value = "商家全选与取消选择")
    public ServerResponse<CartTemVo> selectionByShop(String token, Integer shopId, Boolean shopIsCheck) throws Exception {
        Jedis jedis = jedisPool.getResource();
        SysUser user = tokenUtil.tokenToUser(jedis, token).getData();
        jedis.close();
        return iCartService.selectionByShop(user.getUserId(), shopId, shopIsCheck);
    }

    @LoginRequired
    @PostMapping("add")
    @ApiOperation(value = "增加产品")
    public ServerResponse<CartTemVo> add(HttpServletRequest request, BigDecimal weight, Integer productId, String grade, String token) throws Exception {

        if (productId == null || weight == null) {
            return ServerResponse.createByStatus(ResponseCode.WEIGHT_IS_ZERO.getCode(), ResponseCode.WEIGHT_IS_ZERO.getDesc(), null);
        }
        if (productId == 0 || weight.doubleValue() <= 0) {
            return ServerResponse.createByStatus(ResponseCode.CART_ISEMPTY.getCode(), ResponseCode.CART_ISEMPTY.getDesc(), null);
        }
        SysUser user = tokenUtil.tokenToUser(jedisPool, token).getData();

        Integer customerId = sysDeptCustomerMapper.selectCustomerIdByCustomerUserId(user.getUserId());
        if(null == customerId) return ServerResponse.createByErrorMessage("用户资质未通过，尚未绑定公司，无法添加产品");

        ServerResponse response = iCartService.add(user.getUserId(), productId, grade, weight);
        if (response.getStatus() != 0) {
            return ServerResponse.createByErrorMessage("添加购物车失败");
        }
        Map<String, Object> contentMap = new HashMap<String, Object>();
        contentMap.put("weight", weight);
        contentMap.put("productId", productId);
        contentMap.put("grade", grade);

        BiActionHisParamsVo biActionHisParamsVo = new BiActionHisParamsVo();
        biActionHisParamsVo.setRequest(request);
        biActionHisParamsVo.setAction("购物车增加产品");
        biActionHisParamsVo.setActionUrl("cart/add");
        biActionHisParamsVo.setUserRoleId(user.getUserId());
        //biActionHisParamsVo.setUserRoleName(userRole.getRoleName());
        biActionHisParamsVo.setContent(JsonUtils.objectToJsonStr(contentMap));
        biActionHisParamsVo.setUser(user);
        //用户访问记录
       // actionHistoryService.insertActionHis(biActionHisParamsVo);
        return iCartService.selectCartProducts(user.getUserId());
    }

    //价格需要随着选择的重量变化
    @LoginRequired
    @PostMapping("update")
    @ApiOperation(value = "更新产品")
    public ServerResponse<CartTemVo> update(BigDecimal weight, Integer cartId, String token) throws Exception {
        Jedis jedis = jedisPool.getResource();
        SysUser user = tokenUtil.tokenToUser(jedis, token).getData();
        jedis.close();
        return iCartService.update(user.getUserId(), cartId, weight);
    }

    @LoginRequired
    @PostMapping("delete_product")
    @ApiOperation(value = "删除产品")
    public ServerResponse<CartTemVo> deleteProduct(String cartIds, String token) throws Exception {

        Jedis jedis = jedisPool.getResource();
        SysUser user = tokenUtil.tokenToUser(jedis, token).getData();
        jedis.close();
        return iCartService.deleteProduct(user.getUserId(), cartIds);
    }

    @LoginRequired
    @PostMapping("select_all")
    @ApiOperation(value = "选取全部产品")
    public ServerResponse<CartTemVo> selectAll(String token) throws Exception {

        Jedis jedis = jedisPool.getResource();
        SysUser user = tokenUtil.tokenToUser(jedis, token).getData();
        jedis.close();
        return iCartService.selectOrUnSelect(user.getUserId(), null, Const.Cart.CHECKED);
    }

    @LoginRequired
    @PostMapping("un_select_all")
    @ApiOperation(value = "不选取全部产品")
    public ServerResponse<CartTemVo> unSelectAll(String token) throws Exception {
        
        Jedis jedis = jedisPool.getResource();
        SysUser user = tokenUtil.tokenToUser(jedis, token).getData();
        jedis.close();
        return iCartService.selectOrUnSelect(user.getUserId(), null, Const.Cart.UN_CHECKED);
    }


    @LoginRequired
    @PostMapping("select")
    @ApiOperation(value = "选取产品")
    public ServerResponse<CartTemVo> select(Integer cartId, String token) throws Exception {

        Jedis jedis = jedisPool.getResource();
        SysUser user = tokenUtil.tokenToUser(jedis, token).getData();
        jedis.close();
        return iCartService.selectOrUnSelect(user.getUserId(), cartId, Const.Cart.CHECKED);
    }

    @LoginRequired
    @PostMapping("un_select")
    @ApiOperation(value = "不选取产品")
    public ServerResponse<CartTemVo> unSelect(Integer cartId, String token) throws Exception {

        Jedis jedis = jedisPool.getResource();
        SysUser user = tokenUtil.tokenToUser(jedis, token).getData();
        jedis.close();
        return iCartService.selectOrUnSelect(user.getUserId(), cartId, Const.Cart.UN_CHECKED);
    }

    @LoginRequired
    @PostMapping("get_cart_product_count")
    @ApiOperation(value = "获取购物车内产品数量")
    public ServerResponse<Integer> getCartProductCount(String token) throws Exception {

        Jedis jedis = jedisPool.getResource();
        SysUser user = tokenUtil.tokenToUser(jedis, token).getData();
        jedis.close();
        return iCartService.getCartProductCount(user.getUserId());
    }

    @LoginRequired
    @PostMapping("getCheckedCartProducts")
    @ApiOperation(value = "获取购物车内已选中产品列表")
    public ServerResponse<CartTemVo> getCheckedCartProducts(String token) throws Exception {

        Jedis jedis = jedisPool.getResource();
        SysUser user = tokenUtil.tokenToUser(jedis, token).getData();
        jedis.close();
        return iCartService.selectCheckedCartProducts(user.getUserId());
    }

    /**
     * @Author zhoutao
     * @Description //TODO 根据订单编号来加入购物车
     * @Date 2018/10/11 13:15
     * @Param
     * @return
     **/
    @LoginRequired
    @GetMapping(value = "addCartByOrderNo")
    @ApiOperation(value = "根据订单编号来加入购物车（累加）")
    public ServerResponse addCartByOrderNo(String token, Long orderNo) throws Exception {

        SysUser user = tokenUtil.tokenToUser(jedisPool, token).getData();
        return iCartService.addCartByOrderNo(user.getUserId(), orderNo);
    }

}
